package com.zhang.first.day03;

import com.zhang.first.utils.IntegerSource;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * @title:
 * @author: zhang
 * @date: 2022/1/16 19:10
 */
public class Example12_1 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env
                .addSource(new IntegerSource())
                .keyBy(r -> 1)
                .process(new KeyedProcessFunction<Integer, Integer, IntegerStatistic>() {
                    //声明累加器和定时器状态
                    private ValueState<IntegerStatistic> accumulator;
                    private ValueState<Long> timeTs;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        //Flink程序启动的时候，会先从状态后端寻找状态变量，如果找不到则初始化，如果找不到则实例化
                        accumulator = getRuntimeContext().getState(new ValueStateDescriptor<IntegerStatistic>("acc", Types.POJO(IntegerStatistic.class)));
                        timeTs = getRuntimeContext().getState(new ValueStateDescriptor<Long>("timeTs", Types.LONG));
                    }

                    @Override
                    public void processElement(Integer value, KeyedProcessFunction<Integer, Integer, IntegerStatistic>.Context ctx, Collector<IntegerStatistic> out) throws Exception {
                        if (accumulator.value() == null) {
                            //一条元素到来，直接作为累加器保存，并将累加器输出。
                            accumulator.update(new IntegerStatistic(
                                    value,
                                    value,
                                    value,
                                    1,
                                    value
                            ));
                        } else {
                            IntegerStatistic tmp = accumulator.value();
                            IntegerStatistic newACC = new IntegerStatistic(
                                    Math.max(value, tmp.max),
                                    Math.min(value, tmp.min),
                                    value + tmp.sum,
                                    tmp.count + 1,
                                    (value + tmp.sum) / (tmp.count + 1)
                            );
                            accumulator.update(newACC);
                        }

                        if (timeTs.value() == null) {
                            long currTs = ctx.timerService().currentProcessingTime();
                            long tenSecLater = currTs + 10 * 1000L;
                            //注册10s后的定时器
                            ctx.timerService().registerProcessingTimeTimer(tenSecLater);
                            timeTs.update(tenSecLater);
                        }
                    }

                    @Override
                    public void onTimer(long timestamp, KeyedProcessFunction<Integer, Integer, IntegerStatistic>.OnTimerContext ctx, Collector<IntegerStatistic> out) throws Exception {
                        out.collect(accumulator.value());
                        timeTs.clear();
                    }
                })
                .print();

        env.execute();

    }

    //POJO CLASS
    public static class IntegerStatistic {
        public Integer max;
        public Integer min;
        public Integer sum;
        public Integer count;
        public Integer avg;

        public IntegerStatistic() {
        }

        public IntegerStatistic(Integer max, Integer min, Integer sum, Integer count, Integer avg) {
            this.max = max;
            this.min = min;
            this.sum = sum;
            this.count = count;
            this.avg = avg;
        }

        @Override
        public String toString() {
            return "IntegerStatistic{" +
                    "max=" + max +
                    ", min=" + min +
                    ", sum=" + sum +
                    ", count=" + count +
                    ", avg=" + avg +
                    '}';
        }
    }
}
